package com.abcgroup.hyppo.tools.editors;

import java.beans.PropertyEditorSupport;
import java.beans.PropertyEditorManager;
import java.beans.PropertyEditor;
import java.util.List;
import java.util.LinkedList;
import java.lang.reflect.ParameterizedType;

public class CollectionPropertyEditor<T> extends PropertyEditorSupport {

    protected List<T> internal;

    protected PropertyEditor subEditor;

    public CollectionPropertyEditor() {
        internal = new LinkedList<T>();
        setValue(internal);

        ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
        Class domainClass = (Class) thisType.getActualTypeArguments()[0];

        subEditor = PropertyEditorManager.findEditor(domainClass);
    }

    protected T parseObject(StringBuilder f) {
        return null;
    }

    protected T tryAndParse(StringBuilder f) {
        if (subEditor != null) {
            subEditor.setAsText(f.toString().trim());
            return (T) subEditor.getValue();
        }
        return parseObject(f);
    }

    public void setAsText(final String text) throws IllegalArgumentException {

        StringBuilder sb = new StringBuilder(100);

        int y = 0;
        boolean inLiteral = false;
        while (y < text.length()) {
            if (text.charAt(y) == '\"') {
                inLiteral = !inLiteral;
            } else if (text.charAt(y) == ',' && !inLiteral) {
                internal.add(tryAndParse(sb));
                sb.delete(0, sb.length());
            } else {
                sb.append(text.charAt(y));
            }
            y++;
        }
    }
}
